package com.gzkemays.auth.config;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出处理器
 *
 * <p>单点登出，SpringSecurity 是使用 Cookie 和 Session 记录用户的。所以登出的时候，我们可以将认证中心和各个子系统的 Cookie 进行统一删除。
 *
 * @author gzkemays
 * @since 2021/11/16 12:19
 */
@Component
public class CustomLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
    implements LogoutSuccessHandler {

  @Override
  public void onLogoutSuccess(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Authentication authentication)
      throws IOException, ServletException {
    // 将子系统的cookie删掉
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie cookie : cookies) {
        cookie.setMaxAge(0);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
      }
    }
    super.handle(httpServletRequest, httpServletResponse, authentication);
  }
}
